<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js对象之创建</title>
</head>
<body>
  <ul>
    <li>可使用函数工厂创建对象，通过参数传递对象定制的数据，内部返回包含属性和方法的对象</li>
    <li>可使用构造函数创建对象，构造函数默认返回this，其指向生成的对象，此时如果对象函数赋值为变量，内部this将指向Window</li>
    <li>可使用内置构造函数(如Number,Date,Function,RegExp等)创建对象，其生成对象可通过valueOf获取对应的值</li>
  </ul>
  <script>
    // 函数工厂创建
    function user(name, age) {
      return {
        name,
        age,
        show() {
          console.log(`${this.name} is ${this.age} years old.`)
        }
      }
    }
    // 创建实例
    const miracle1 = user('Miracle', 35)
    const jack1 = user('Jack', 40)
    miracle1.show()         // Miracle is 35 years old.
    jack1.show()            // Jack is 40 years old.
    // 构造函数创建
    function User(name, age) {
      this.name = name
      this.age = age
    }
    User.prototype.show = function () {
      console.log(this)
      console.log(`${this.name} is ${this.age} years old.`)
    }
    const miracle2 = new User('Miracle', 35)
    const jack2 = new User('Jack', 40)
    miracle2.show()               // Miracle is 35 years old.
    jack2.show()                  // Jack is 40 years old.
    const show = miracle2.show
    show()                        // Window
    // 内置构造函数
    const num = Number(1)
    console.log(num.valueOf())
    const date = new Date()        // 1
    console.log(date.valueOf())    // 1591879551438
    const reg = new RegExp(/\d+/)
    console.log(reg.valueOf())     // /\d+/
    console.log(reg.test('1984'))  // true
    const Func = new Function('name', 'age', `
      this.name = name
      this.age = age
      this.show = function() {
        console.log(this.name + ' is ' + this.age + ' years old.')
      }
    `)
    const func = new Func('Miracle', 35)
    console.log(func.valueOf())    // {name: "Miracle", age: 35, show: ƒ}
    func.show()                    // Miracle is 35 years old.
  </script>
</body>
</html>
